<?php
namespace app\framework\lib;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\JsonFormatter;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

class Log
{

    /**
     * @var LoggerInterface
     */
    private static $logger;

    /**
     * 业务名称
     * @var string
     */
    private static $name = 'backend';

    /**
     * 文件日志路径
     * @var string
     */
    private static $path ="";

    /**
     * 所属环境
     * @var string
     */
    private static $env = "dev";


    private static $max_files = 0;

    public static function __callStatic($name, $arguments)
    {
        $config = Config::getInstance();
        $logConfig = $config->log;
        self::$name = $logConfig["name"];
        self::$path = $logConfig["path"];
        self::$env =  $logConfig["env"];
        self::$max_files = $logConfig["max_files"];
        $message = empty($arguments[0]) ? '' : $arguments[0];
        $context = empty($arguments[1]) ? [] : $arguments[1];
        return self::getLogger()->$name($message, $context);
    }

    public static function getLogger()
    {

        if (self::$logger === null) {
            self::$logger = new Logger(self::$name);
            $formatter = new JsonFormatter();
            $formatter->setDateFormat('Y-m-d H:i:s');
            if (self::$env == "dev") {
                $streamHandler = new StreamHandler("php://stdout");
                $streamHandler->setFormatter($formatter);
                $formatter->setJsonPrettyPrint(false);
                self::$logger->pushHandler($streamHandler);
            } else {
                $formatter->setJsonPrettyPrint(true);
                $infoFileHandler = new RotatingFileHandler(self::$path. '/info.log',2,LogLevel::INFO,true);
                $infoFileHandler ->setFormatter($formatter);
                self::$logger->pushHandler($infoFileHandler);
                $warningFileHandler = new RotatingFileHandler(self::$path. '/warn.log',2,LogLevel::WARNING,true);
                $warningFileHandler->setFormatter($formatter);
                self::$logger->pushHandler($warningFileHandler);
                $errorFileHandler = new RotatingFileHandler(self::$path. '/error.log',2,LogLevel::ERROR,true);
                $errorFileHandler->setFormatter($formatter);
                self::$logger->pushHandler($errorFileHandler);
            }
        }
        return self::$logger;
    }


}